package com.future.lock.home.activity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.future.baselib.activity.BaseActivity;
import com.future.baselib.entity.MessageEvent;
import com.future.baselib.utils.EventBusUtil;
import com.future.baselib.view.CustomViewCenterDialog;
import com.future.lock.R;
import com.future.lock.common.Constants;
import com.future.lock.common.MyApp;
import com.future.lock.common.RefreshDataUtils;
import com.future.lock.common.http.HttpUtils;
import com.future.lock.common.http.response.DefaultHttpResponse;
import com.hiflying.smartlink.OnSmartLinkListener;
import com.hiflying.smartlink.SmartLinkedModule;
import com.hiflying.smartlink.v7.MulticastSmartLinker;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class AddGatewayStep3Activity extends BaseActivity implements OnSmartLinkListener {

    @BindView(R.id.textView)
    TextView textView;
    @BindView(R.id.view_line)
    View viewLine;
    private String wifiSSID;
    private String pwd;
    private MulticastSmartLinker smartLinker;

    private String errorMessage = "网关匹配超时，请检查设置并重试！";

    private int connTimeOut = 59;
    private boolean isConnecting = true;

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1 && isConnecting) {
                textView.setText("等待网关链接WiFi，请稍等...(" + connTimeOut-- + "s)");
                handler.sendEmptyMessageDelayed(1, 1000);
            }
        }
    };
    private String id;
    private String mac;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initContentView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_add_gateway_step3);
        ButterKnife.bind(this);
    }

    @Override
    protected void initView() {
        setTitle("");
        viewLine.setVisibility(View.GONE);
        setTitleLeft(R.mipmap.ic_exit, v -> finish());

        smartLinker = MulticastSmartLinker.getInstance();
        smartLinker.setOnSmartLinkListener(this);
        try {
            smartLinker.start(getApplicationContext(), pwd, wifiSSID);
            smartLinker.setTimeoutPeriod(60 * 1000);
        } catch (Exception e) {
            onTimeOut();
        }
        handler.sendEmptyMessage(1);

        getErrorText();
    }

    private void getErrorText() {
        HttpUtils.getHttpApi()
                .addGatewayFail()
                .enqueue(new Callback<String>() {
                    @Override
                    public void onResponse(Call<String> call, Response<String> response) {
                        DefaultHttpResponse httpResponse = new DefaultHttpResponse();
                        httpResponse.parse(response.body());
                        if (httpResponse.success == 1) {
                            errorMessage = httpResponse.data;
                        }
                    }

                    @Override
                    public void onFailure(Call<String> call, Throwable t) {

                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        smartLinker.setOnSmartLinkListener(null);
        isConnecting = false;
    }

    @Override
    protected void initLogic() {

    }

    @Override
    protected void getBundleExtras(Bundle extras) {
        wifiSSID = extras.getString("ssid");
        pwd = extras.getString("pwd");
    }

    @Override
    public void onLinked(SmartLinkedModule smartLinkedModule) {
        id = smartLinkedModule.getId();
        mac = smartLinkedModule.getMac();
        StringBuffer buffer = new StringBuffer(mac);
        for (int i = buffer.length()-2; i > 0 ; i--) {
            if (i%2==0) {
                buffer.insert(i,",");
            }
        }
        mac = buffer.toString();

        isConnecting = false;

        HttpUtils.getHttpApi().addGateway(MyApp.getUserToken(), mac).enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                DefaultHttpResponse httpResponse = new DefaultHttpResponse();
                httpResponse.parse(response.body());
                if (httpResponse.success == 1) {
                    textView.setText("网关链接成功!");
                    String gateway_id = "";
                    try {
                        JSONObject object = new JSONObject(httpResponse.msg);
                        gateway_id = object.optString("gateway_id");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    showSuccessDialog(gateway_id);
                } else {
                    if (httpResponse.code == 112) {
                        RefreshDataUtils.logout(AddGatewayStep3Activity.this);
                    }
                    toast(httpResponse.msg);
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                toast(t.getMessage());
            }
        });
    }

    @Override
    public void onCompleted() {

    }

    private void showSuccessDialog(String gateway_id) {
        View rootView = getLayoutInflater().inflate(R.layout.dialog_default, null);
        ((TextView) rootView.findViewById(R.id.tv_message)).setText("是否要继续匹配智能锁？");
        ((TextView) rootView.findViewById(R.id.tv_title)).setText("网关匹配成功");
        Button btnCancel = (Button) rootView.findViewById(R.id.btn_cancel);
        btnCancel.setText("暂不匹配");
        btnCancel.setOnClickListener(view -> startActivity(AddMachineActivity.class));
        Button btnOk = (Button) rootView.findViewById(R.id.btn_ok);
        btnOk.setText("立即匹配");
        btnOk.setOnClickListener(view -> {
            Bundle bundle = new Bundle();
            bundle.putBoolean("addLock", true);
            bundle.putString("gateway_id",gateway_id);
            startActivity(AddMachineActivity.class, bundle);
        });
        new CustomViewCenterDialog(this)
                .setView(rootView)
                .builder()
                .setCancelable(false)
                .show();
    }

    @Override
    public void onTimeOut() {
        isConnecting = false;
        View rootView = getLayoutInflater().inflate(R.layout.dialog_gateway_fail, null);
        ((TextView) rootView.findViewById(R.id.tv_content)).setText(Html.fromHtml(errorMessage));
        rootView.findViewById(R.id.btn_ok).setOnClickListener(view -> startActivity(AddGatewayStep1Activity.class));
        new CustomViewCenterDialog(this).setView(rootView).builder().setCancelable(false).show();
    }

    @Override
    protected void onStop() {
        super.onStop();
        isConnecting = false;
    }
}
